package com.alogic.ac.loader.acm.xscript;

import com.alogic.ac.AccessControlModel;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.alogic.xscript.plugins.Segment;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 新建一个ACM模型
 *
 * @since 1.6.12.54 [20191219]
 */
public class ACMNew extends Segment {
    /**
     * 当前节点的上下文id
     */
    protected String cid = "$acm-object";

    protected String $id;
    protected String $maxThread = "10";
    protected String $timesPerMin = "100000";
    protected String $priority = "0";

    public ACMNew(String tag, Logiclet p) {
        super(tag, p);

        registerModule("acm-add-aci",ACMAddAci.class);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);
        $id = PropertiesConstants.getRaw(p, "id", "");

        $maxThread = PropertiesConstants.getRaw(p, "maxThread", $maxThread);
        $timesPerMin = PropertiesConstants.getRaw(p, "timesPerMin", $timesPerMin);
        $priority = PropertiesConstants.getRaw(p, "priority", $priority);

        cid = PropertiesConstants.getString(p,"cid", cid,true);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        String id = PropertiesConstants.transform(ctx,$id,"");
        if (StringUtils.isNotEmpty(id)){
            AccessControlModel acm = new MyAccessControlModel(id,
                    PropertiesConstants.transform(ctx,$maxThread,10),
                    PropertiesConstants.transform(ctx,$timesPerMin,100000),
                    PropertiesConstants.transform(ctx,$priority,0));
            ctx.setObject(cid,acm);
            super.onExecute(root,current,ctx,watcher);
        }
    }

    /**
     * 自己的实现
     */
    public static class MyAccessControlModel extends AccessControlModel.Default{
        public MyAccessControlModel(String id, int maxThread, int timesPerMin, int priority){
            super(id);
            this.maxThread = maxThread;
            this.maxTimesPerMin = timesPerMin;
            this.priority = priority;
        }
    }
}
